#pragma once
#include <string>
#include <iostream>
#include <fstream>
#include <memory>
#include <ctime>
#include <sstream>
#include <filesystem>
#include <unistd.h>
#include "mutex.hpp"

namespace LogMudule
{
    using namespace std;
    using namespace MutexModel;

    // 分为日志信息与落盘方式（显示屏或者文件）

    //  默认路径和日志名称
    const string defaultpath = "./log/";
    const string defaultname = "log.txt";

    // 日志等级
    enum class LogLevel
    {
        DEBUG,
        INFO,
        WARNING,
        ERROR,
        FATAL
    };

    // 根据时间戳，获取可读性较强的时间信息
    string GetCurTime()
    {
        time_t tm = time(nullptr);
        struct tm curr;
        localtime_r(&tm, &curr);
        stringstream ss;
        ss << curr.tm_year + 1900 << "-"
           << curr.tm_mon << "-"
           << curr.tm_mday << " "
           << curr.tm_hour << ":"
           << curr.tm_min << ":"
           << curr.tm_sec;
        return ss.str();
    }
    string LogLevelToString(LogLevel level)
    {
        switch (level)
        {
        case LogLevel::DEBUG:
            return "DEBUG";
        case LogLevel::INFO:
            return "INFO";
        case LogLevel::WARNING:
            return "WARNING";
        case LogLevel::ERROR:
            return "ERROR";
        case LogLevel::FATAL:
            return "FATAL";
        default:
            return "UNKNOWN";
        }
    }

    // 策略模式构建落盘方式
    class LogStrategy
    {
    public:
        virtual ~LogStrategy() = default;
        virtual void SyncLog(const string &message) = 0; // 不同模式的刷新方式
    };

    class ConsoleLogStrategy : public LogStrategy
    {
    public:
        virtual ~ConsoleLogStrategy()
        {
        }
        void SyncLog(const string &message)
        {
            LockGuard lock(_mutex);
            cout << message << endl;
        }
    private:
        Mutex _mutex;
    };

    class FileLogStrategy : public LogStrategy
    {
    public:
        ~FileLogStrategy()
        {
        }
        FileLogStrategy(const string &logpath = defaultpath, const string &logname = defaultname)
            : _logpath(logpath), _logname(logname)
        {
            LockGuard lock(_mutex);
            if (std::filesystem::exists(_logpath))
                return;
            try
            {
                std::filesystem::create_directories(_logpath);
            }
            catch (const std::filesystem::filesystem_error &e)
            {
                std::cerr << e.what() << '\n';
            }
        }
        void SyncLog(const string &message)
        {
            LockGuard lock(_mutex);
            string log = _logpath + _logname;
            ofstream out(log.c_str(), ios::app); // 追加⽅式
            if (!out.is_open())
                return;
            out << message << "\n";
            out.close();
        }

    private:
        Mutex _mutex;
        const string &_logpath;
        const string &_logname;
    };

    class Logger
    {
    public:
        Logger()
        {
            UseConsoleStrategy();
        }
        void UseConsoleStrategy()
        {
            _strategy = make_unique<ConsoleLogStrategy>();
        }
        void UseFileLogStrategy()
        {
            _strategy = make_unique<FileLogStrategy>();
        }
        class LogMessage
        {
        public:
            LogMessage(LogLevel type, string filename, int line, Logger &logger) : _type(type),
                                                                                   _curr_time(GetCurTime()),
                                                                                   _pid(getpid()),
                                                                                   _filename(filename),
                                                                                   _line(line),
                                                                                   _logger(logger)
            {
                std::stringstream ssbuffer;
                ssbuffer << "[" << _curr_time << "] "
                         << "[" << LogLevelToString(type) << "] "
                         << "[" << _pid << "] "
                         << "[" << _filename << "] "
                         << "[" << _line << "]"
                         << " - ";
                _loginfo = ssbuffer.str();
            }

            template <typename T>
            LogMessage &operator<<(const T &info)
            {
                stringstream ssbuffer;
                ssbuffer << info;
                _loginfo += ssbuffer.str();
                return *this;
            }
            ~LogMessage()
            {
                if (_logger._strategy)
                {
                    _logger._strategy->SyncLog(_loginfo);
                }
            }

        private:
            LogLevel _type;         // 日志等级
            std::string _curr_time; // 日志时间
            pid_t _pid;             // 写入日志的时间
            std::string _filename;  // 对应的文件名
            int _line;              // 对应的文件⾏号
            Logger &_logger;        // 引用外部logger类, ⽅便使用策略进行刷新
            std::string _loginfo;   // 一条合并完成的，完整的日志信息
        };
        LogMessage operator()(LogLevel type, string filename, int line)
        {
            return LogMessage(type, filename, line, *this);
        }
        ~Logger()
        {
            _strategy = make_unique<FileLogStrategy>();
        }

    private:
        std::unique_ptr<LogStrategy> _strategy;
    };
    Logger logger;

// 使用宏，可以进行代码插⼊，⽅便随时获取文件名和行号
#define LOG(type) logger(type, __FILE__, __LINE__)
// 提供选择使用何种日志策略的方法
#define ENABLE_CONSOLE_LOG_STRATEGY() logger.UseConsoleStrategy()
#define ENABLE_FILE_LOG_STRATEGY() logger.UseFileStrategy()

}